package siga.modelo;

import java.io.*;
import java.util.*;

public class CadastrarDisciplina{
	public void cadastro(Disciplina d, String curso) throws Exception{
		int numCurso = 0;
		try{
			String linha;
			ArrayList<Disciplina> disciplinas = new ArrayList<Disciplina>();
			
			FileReader     frc = new FileReader("CadastroCursos.txt");
			BufferedReader brc = new BufferedReader(frc);
			
			String leituraCurso;
			
			while((leituraCurso = brc.readLine()) != null){
				String[] s = leituraCurso.split("\\|");
				if (s[1].equals(curso)){
					numCurso = Integer.parseInt(s[0]);
				}
			}
			
			FileReader     fr = new FileReader("cadastroDisciplinas.txt");
			BufferedReader br = new BufferedReader(fr);
			FileWriter     fw = new FileWriter("cadastroDisciplinas.txt", true);
			BufferedWriter bw = new BufferedWriter(fw);
			
			String[] leitura;
			while((linha = br.readLine())!=null){
				leitura = linha.split("\\|");
				
				String nomeDisciplina = leitura[1];
				String codigoDisciplina = leitura[2];
				int creditosDisciplina = Integer.parseInt(leitura[3]);
				
				Disciplina di = new Disciplina(nomeDisciplina, codigoDisciplina, creditosDisciplina);
				disciplinas.add(di);
			}
			if(disciplinas.contains(d)){
				throw new Exception("Cadastro Existente.");
			}
			else{
				String entrada = numCurso + "|" + d.toString();
				bw.append(entrada,0,entrada.length());
				bw.newLine();
				bw.flush();
				fw.close();
				bw.close();
				br.close();
				fr.close();
			}
		} catch (FileNotFoundException ex) {
			try {
				FileWriter     fw = new FileWriter("cadastroDisciplinas.txt");
				BufferedWriter bw = new BufferedWriter(fw);
				
				String entrada = numCurso + "|" + d.toString();
				bw.append(entrada,0,entrada.length());
				bw.newLine();
				bw.flush();
				fw.close();
				bw.close();
			} catch (FileNotFoundException e1) {}
		}
	}
}
